<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px"
      @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input clearable style="width: 240px" v-model="queryParams.search.keyword" placeholder="请输入商户名/法人/联系方式"
          clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.search.status" placeholder="商户状态" clearable style="width: 100%">
          <el-option v-for="(i,index) in ['未开启','运营中']" :key="index" :label="i" :value="index" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getDataList"></right-toolbar>
    </el-row>
    <el-table :data="dataList" v-loading="loading" style="width: 100%;">

      <el-table-column type="index" label="序号" width="60"></el-table-column>
      <el-table-column prop="name" width="120" label="商户名" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="loginName" width="140" label="账号" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="mobile" width="120" label="联系方式" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="legalPersonName" width="120" label="法人" align="center" :show-overflow-tooltip="true" />

      <el-table-column label="状态" width="80" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 0" type="warning">未开启</el-tag>
          <el-tag v-else type="success">运营中</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="收费模式" align="center" width="120" prop="type">
        <template slot-scope="scope">
          {{scope.row.type==1?'平台扣费':'按月缴纳'}}
        </template>
      </el-table-column> -->
      <el-table-column prop="licenseId" width="240" label="统一社会信用代码" align="center" :show-overflow-tooltip="true" />
      <!-- <el-table-column prop="startTime" width="120" label="有效开始日期" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="endTime" width="120" label="有效结束日期" align="center" :show-overflow-tooltip="true" /> -->
      <!-- <el-table-column prop="revenue" width="200" label="收益总金额" align="center" :show-overflow-tooltip="true" /> -->


      <el-table-column prop="createTime" width="200" label="创建时间" align="center" :show-overflow-tooltip="true" />
      <el-table-column prop="location" label="所在地址" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" fixed="right" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="preview(scope.row)"
            v-hasPermi="['business:driver:list']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:driver:list']">修改</el-button>

          <el-dropdown>
            <span class="el-dropdown-link">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-plus">
                <el-button size="mini" type="text" @click="previewOrder(scope.row)"
                  v-hasPermi="['business:driver:list']">结算订单</el-button>
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-circle-plus">
                <el-button size="mini" type="text" @click="info = scope.row;showRecharge = true;"
                  v-hasPermi="['business:driver:list']">余额充值</el-button>
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete">
                <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                  v-hasPermi="['business:driver:list']">删除</el-button></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getDataList" />
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog title="商户信息" :visible.sync="showInfo" width="60%" top="20px">
      <el-descriptions :column="3">
        <el-descriptions-item label="商户名">{{info.name}}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{info.mobile}}</el-descriptions-item>
        <el-descriptions-item label="登录名">{{info.loginName}}</el-descriptions-item>
        <el-descriptions-item label="法人">{{info.legalPersonName}}</el-descriptions-item>
        <el-descriptions-item label="社会信用代码">{{info.licenseId}}</el-descriptions-item>
        <el-descriptions-item label="余额">{{info.balance}}元</el-descriptions-item>

        <el-descriptions-item label="所在地址">{{info.location}}</el-descriptions-item>
      </el-descriptions>
      <div class="driver_data">
        <div class="date">
          <el-select v-model="query.search.status" size="mini" placeholder="订单状态" clearable v-if="activeName == '1'">
            <el-option v-for="i in statusList" :key="i.value" :label="i.label" :value="i.value" />
          </el-select>
          <div class="margin_right"></div>
          <el-date-picker v-model="dataDate" type="daterange" range-separator="至" start-placeholder="开始日期" size="mini"
            value-format="yyyy-MM-dd" @change="fetchData" end-placeholder="结束日期">
          </el-date-picker>
          <div class="margin_right"></div>
          <el-button size="mini" type="primary" @click="fetchData">查询</el-button>
          <el-button size="mini" @click="refreshQuery">重置</el-button>
        </div>
      </div>
      <el-tabs v-model="activeName" class="tab_title" @tab-click="onTabChange">
        <el-tab-pane label="订单记录" name="1">
          <el-table :data="orderList" style="width: 100%" height="400">
            <el-table-column prop="orderNumber" label="订单编号" align="center" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag type="info" v-if="scope.row.status == 10">未支付</el-tag>
                <el-tag type="warning" v-if="scope.row.status == 20">待发货</el-tag>
                <el-tag v-if="scope.row.status == 30">待收货</el-tag>
                <el-tag type="success" v-if="scope.row.status == 40">已完成</el-tag>
                <el-tag type="info" v-if="scope.row.status == 50">已取消</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" align="center" :show-overflow-tooltip="true" />
            <el-table-column prop="meetAmount" label="应付金额" align="right" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.meetAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column prop="paidAmount" label="实付金额" align="center" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.paidAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column prop="franchiseeName" label="加盟商" align="left" :show-overflow-tooltip="true" />
          </el-table>
          <pagination v-show="orderTotal>0" :total="orderTotal" layout="prev, pager, next" :page.sync="query.pageNum"
            :limit.sync="query.pageSize" @pagination="getOrder" />
        </el-tab-pane>
        <el-tab-pane label="充值记录" name="2">
          <el-table :data="rechargeList" style="width: 100%" height="400">
            <el-table-column prop="orderNumber" label="订单编号" align="center" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag type="info" v-if="scope.row.status == 10">未支付</el-tag>
                <el-tag type="warning" v-if="scope.row.status == 20">待发货</el-tag>
                <el-tag v-if="scope.row.status == 30">待收货</el-tag>
                <el-tag type="success" v-if="scope.row.status == 40">已完成</el-tag>
                <el-tag type="info" v-if="scope.row.status == 50">已取消</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" align="center" :show-overflow-tooltip="true" />
            <el-table-column prop="meetAmount" label="应付金额" align="right" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.meetAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="paidAmount" label="实付金额" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    {{scope.row.paidAmount.toFixed(2)}}
                  </template>
                </el-table-column> -->
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="结算记录" name="3">
          <el-table :data="settlementList" style="width: 100%" height="400">
            <el-table-column prop="createTime" label="时间" width="180"  />
            
            <el-table-column prop="meetAmount" label="应付金额" >
              <template slot-scope="scope">
                {{scope.row.meetAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column prop="paidAmount" label="实付金额" >
              <template slot-scope="scope">
                {{scope.row.meetAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <el-table-column prop="payerName" label="结算人" />
            <el-table-column prop="settlementType" label="结算方式" >
              <template slot-scope="scope">
                <span v-if="scope.row.settlementType == 10">微信</span>
                <span v-if="scope.row.settlementType == 20">现金</span>
              </template>
            </el-table-column>
            <el-table-column prop="settlerName" label="操作员" />
          </el-table>
          <pagination v-show="orderTotal>0" :total="orderTotal" layout="prev, pager, next" :page.sync="query.pageNum"
            :limit.sync="query.pageSize" @pagination="getOrder" />
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showInfo = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog title="待结算订单" :visible.sync="showOrder" width="60%" top="20px">
      <div>
        <el-row>
          <el-col :span="8">
            <div class="recharge">
              <div class="label">待结算金额：</div>{{debts}}
            </div>
          </el-col>
          <el-col :span="8">
            <div class="recharge">
              <div class="label">结算金额：</div><el-input type="number" size="mini" v-model="payInfo.paidAmount" min="0" />
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <div class="recharge">
              <div class="label">付款方式：</div>
              <el-select v-model="payInfo.settlementType" size="mini" placeholder="付款方式" clearable>
                <el-option v-for="i in payTypeList" :key="i.value" :label="i.label" :value="i.value" />
              </el-select>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="recharge">
              <div class="label"> 付款人：</div><el-input size="mini" v-model="payInfo.settler" />
            </div>
          </el-col>
        </el-row>




      </div>
      <div class="driver_data">
        <div class="date">
          <span>订单总金额：{{orderSelectedAmount}}</span>
          <div class="margin_right"></div>
          <el-button size="mini" @click="getSettlementOrder">重置</el-button>
        </div>
      </div>
      <el-tabs v-model="activeName2" class="tab_title">
        <el-tab-pane label="待结算订单" name="1">
          <el-table :data="settlementOrderList" style="width: 100%" height="400" @selection-change="onSelect">
            <el-table-column type="selection" />
            <el-table-column prop="orderNumber" label="订单编号" align="center" :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag type="info" v-if="scope.row.status == 10">未支付</el-tag>
                <el-tag type="warning" v-if="scope.row.status == 20">待发货</el-tag>
                <el-tag v-if="scope.row.status == 30">待收货</el-tag>
                <el-tag type="success" v-if="scope.row.status == 40">已完成</el-tag>
                <el-tag type="info" v-if="scope.row.status == 50">已取消</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" align="center" :show-overflow-tooltip="true" />
            <el-table-column prop="meetAmount" label="应付金额" align="right" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{scope.row.meetAmount.toFixed(2)}}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="paidAmount" label="实付金额" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    {{scope.row.paidAmount.toFixed(2)}}
                  </template>
                </el-table-column> -->
          </el-table>

        </el-tab-pane>
        
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="payOrder">一键结算</el-button>
      </span>
    </el-dialog>
    <el-dialog title="余额充值" :visible.sync="showRecharge" width="30%">
      <div>
        <div class="recharge">
          <div class="label">当前余额：</div>{{info.balance}}
        </div>
        <div class="recharge">
          <div class="label">充值金额：</div><el-input type="number" size="mini" v-model="rechargeInfo.money" min="0" />
        </div>
        <div class="recharge">
          <div class="label"> 充值人：</div><el-input size="mini" v-model="rechargeInfo.name" />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="recharge">充 值</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    page,
    deleteById,
    addOrUpdate,
    recharge,
    settlement,
    settlementList,
    settlementOrder
  } from "@/api/business/franchiseeinfo";
  import {
    page as getOrder
  } from "@/api/business/orderinfo";
  import AddOrUpdate from './addOrUpdate'
  export default {
    dicts: ['sys_franchiseeinfo_status', 'sys_normal_disable', 'sys_user_sex'],
    data() {
      return {
        debts:0,//待结算总金额
        settlementList:[],
        rechargeList:[],
        activeName: '1',
        activeName2: '1',
        showInfo: false,
        showRecharge: false,
        orderSelectedAmount: 0,
        info: {},
        orderList: [],
        rechargeInfo: {},
        orderTotal: 0,
        loading: true,
        loading2: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        // 总条数
        total: 0,
        //表格数据
        dataList: [],
        showOrder: false,
        payTypeList: [{
            label: '微信',
            value: '10'
          },
          {
            label: '现金',
            value: '20'
          },
        ],
        statusList: [{
            label: '未支付',
            value: '10'
          },
          {
            label: '支付成功（待发货）',
            value: '20'
          },
          {
            label: '待收货',
            value: '30'
          },
          {
            label: '已完成',
            value: '40'
          },
          {
            label: '已取消',
            value: '50'
          },
        ],
        selectedOrder: [],
        // 弹出层标题
        title: "",
        // 表单参数
        // 显示搜索条件
        showSearch: true,
        form: {},
        // 日期范围
        dateRange: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          search: {
            keyword: '',
            agentId: ''
          }
        },
        dataList: [],
        rules: {},
        addOrUpdateVisible: false,
        orderList: [],
        comerecordList: [],
        dataDate: [],
        query: {
          pageNum: 1,
          pageSize: 7,
          search: {
            status: '',
            startDate: '',
            endDate: ''
          },
        },
        payInfo: {},
        settlementOrderList:[]
      }
    },
    components: {
      AddOrUpdate
    },
    created() {
      this.getDataList();
      this.initPage();
    },
    methods: {
      fetchData(){
        if(this.activeName == '1'){
          this.getOrder();
        }else if(this.activeName == '2'){
          this.getOrder();
        }else{
          this.getSettlement();
        }
      },
      onTabChange(tab,event){
        if(tab.name == '1'){
          this.getOrder();
        }else if(tab.name == '2'){
          this.getOrder();
        }else{
          this.getSettlement();
        }
      },
      // 结算记录
      getSettlement(){
        settlementList({
          pageNum:1,
          pageSize:1000,
          search:{
            startDate:this.dataDate[0]?this.dataDate[0]:'',
            endDate:this.dataDate[1]?this.dataDate[1]:'',
            // agentId:this.info.id
          }
        }).then(res=>{
          this.settlementList = res.data.list
        })
      },
      // 未结算订单
      getSettlementOrder(){
        settlementOrder({
          pageNum:1,
          pageSize:1000,
          search:{
            agentId:this.info.id
          }
        }).then(res=>{
          this.settlementOrderList = res.data
          var num = 0;
          for (var i = 0; i < res.data.length; i++) {
            num += res.data[i].meetAmount * 100;
          }
          this.debts = (num / 100).toFixed(2);
        })
      },
      recharge(e) {
        if (!this.rechargeInfo.money) {
          this.$message({
            type: 'info',
            message: '请输入充值金额'
          });
          return
        }
        if (this.rechargeInfo.money < 1) {
          this.$message({
            type: 'info',
            message: '请输入正确金额'
          });
          return
        }
        if (!this.rechargeInfo.name) {
          this.$message({
            type: 'info',
            message: '请输入充值人姓名'
          });
          return
        }
        recharge(this.info.id + '/' + this.rechargeInfo.money + '/' + this.rechargeInfo.name).then(res => {
          this.$message({
            type: 'success',
            message: '充值成功'
          });
          this.resetQuery();
          this.showRecharge = false;
          this.rechargeInfo = {}
        })
      },
      refreshQuery() {
        this.query.search = {
          agentId: this.query.search.agentId
        }
        this.dataDate = []
        this.getOrder()
      },
      initPage() {

      },
      payOrder() {
        const info = this.payInfo;
        info.meetAmount = this.orderSelectedAmount;
        info.orderIdList = [];
        for (var i = 0; i < this.selectedOrder.length; i++) {
          info.orderIdList.push(this.selectedOrder[i].id);
        }
        if (!info.paidAmount) {
          this.$message({
            type: 'info',
            message: '请输入结算金额'
          });
          return
        }
        if (!info.settlementType) {
          this.$message({
            type: 'info',
            message: '请选择结算方式'
          });
          return
        }
        if (!info.settler) {
          this.$message({
            type: 'info',
            message: '请输入结算人名称'
          });
          return
        }
        if (info.orderIdList == 0) {
          this.$message({
            type: 'info',
            message: '请勾选要结算的订单'
          });
          return
        }
         const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        settlement(info).then(res => {
          this.$message({
            type: 'success',
            message: '操作成功'
          });
          loading.close()
          this.showOrder = false;
          this.refreshQuery;

        }).catch((e) => {
          this.loading2 = false
          loading.close()
        })
      },
      getOrder() {
        console.log('info', this.info.id)
        this.query.search.agentId = this.info.id
        getOrder(this.query).then(res => {
          this.orderList = res.data.list
          this.loading2 = false
          this.orderTotal = parseInt(res.data.total);
        }).catch((e) => {
          this.loading2 = false
        })
      },
      preview(e) {
        this.info = e;
        this.showInfo = true;
        this.loading2 = true
        this.getOrder()
      },
      previewOrder(e) {
        this.info = e;
        this.payInfo = {}
        this.payInfo.agentId = e.id
        this.showOrder = true;
        this.loading2 = true
        this.getSettlementOrder()
      },
      onSelect(e) {
        console.log('选择数据', e)
        this.selectedOrder = e;
        var num = 0;
        for (var i = 0; i < e.length; i++) {
          num += e[i].meetAmount * 100;
        }
        this.orderSelectedAmount = (num / 100).toFixed(2);
      },
      // 获取数据列表
      getDataList() {
        this.loading = true;
        page(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.list;
          this.total = parseInt(response.data.total);
          this.loading = false;
        }).catch(res => {
          this.loading = false
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getDataList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.userId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.addOrUpdateVisible = true;
        this.title = "添加";
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init({})
        })
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.addOrUpdateVisible = true;
        this.title = "修改";
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(row)
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('确定要删除选中的数据项？').then(function() {
          return deleteById(ids);
        }).then(() => {
          this.getDataList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          search: {
            keyword: '',
            agentId: ''
          }
        };
        this.getDataList()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .recharge {
    display: flex;
    align-items: center;
    margin: 10px 0;

    .label {
      width: 100px;
      text-align: right;
    }
  }

  .driver_data {
    position: relative;

    .date {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 1;
      display: flex;
      align-items: center;
    }
  }

  .margin_right {
    margin-right: 10px;
  }
</style>
<style>
  .recharge .el-input {
    width: 200px;
  }
</style>
